package com.fuxi.cloud.desreport.service.a;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fuxi.cloud.common.expetion.JimuReportException;
import com.fuxi.cloud.common.util.ApiAssert;
import com.fuxi.cloud.common.util.DesUtils;
import com.fuxi.cloud.common.util.oConvertUtils;
import com.fuxi.cloud.common.vo.Result;
import com.fuxi.cloud.config.client.JmReportTokenClient;
import com.fuxi.cloud.desreport.dao.JimuReportDbDao;
import com.fuxi.cloud.desreport.dao.JimuReportDbParamDao;
import com.fuxi.cloud.desreport.entity.JmReportDataSource;
import com.fuxi.cloud.desreport.entity.JmReportDb;
import com.fuxi.cloud.desreport.entity.JmReportDbField;
import com.fuxi.cloud.desreport.entity.JmReportDbParam;
import com.fuxi.cloud.desreport.service.*;
import com.fuxi.cloud.dyndb.JmreportDataSourceCachePool;
import com.fuxi.cloud.dyndb.JmreportDynamicDbUtil;
import com.fuxi.cloud.dyndb.util.JmreportSqlUtils;
import com.fuxi.cloud.dyndb.vo.JmreportDynamicDataSourceVo;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.minidao.pojo.MiniDaoPage;
import org.jeecgframework.minidao.util.SnowflakeIdWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fuxi.cloud.desreport.b.c;

/**
 * a
 *
 * @Author: 扫地僧
 * @CreateTime: 2021-05-03
 */
@Service("jmReportDbServiceImpl")
public class h implements IJmReportDbService {
    private static final Logger a = LoggerFactory.getLogger(h.class);
    @Autowired
    private IJmReportDbParamService jmReportParamService;
    @Autowired
    private IJmReportDbFieldService reportDbFieldService;
    @Autowired
    private IJmReportDbSourceService jmReportDbSourceService;
    @Autowired
    private JmreportDynamicDbUtil jmreportDynamicDbUtil;
    @Autowired
    private JmReportTokenClient jimuTokenClient;
    @Autowired
    private JimuReportDbDao reportDbDao;
    @Autowired
    private JimuReportDbParamDao dbParamDao;
    @Autowired
    private IJimuReportService jimuReportService;

    public h() {
    }

    @Override
    @Transactional
    public JmReportDb saveDb(JmReportDb reportDb) {
        if ("1".equals(reportDb.getIsPage())) {
            List<JmReportDb> var2 = this.reportDbDao.selectList(reportDb.getJimuReportId());
            var2.forEach((var1) -> {
                var1.setIsPage("0");
                if (ObjectUtil.isEmpty(var1.getDbSource())) {
                    var1.setDbSource("");
                }

                this.a(var1);
            });
        }

        String var8;
        if ("0".equals(reportDb.getDbType())) {
            var8 = reportDb.getDbSource();
            if (oConvertUtils.isNotEmpty(var8)) {
                JmReportDataSource var3 = this.jmReportDbSourceService.getById(var8);
                if (var3 != null) {
                    String var4 = var3.getDbType();
                    reportDb.setDbSourceType(var4);
                }
            }

            if (oConvertUtils.isEmpty(reportDb.getDbSourceType())) {
                String var9 = null;

                try {
                    var9 = com.fuxi.cloud.desreport.b.d.getDatabaseType();
                } catch (SQLException var7) {
                    a.error("jm报表保存数据集,获取数据库类型失败" + var7.getMessage());
                }

                reportDb.setDbSourceType(var9);
                reportDb.setDbSource("");
            }
        }

        if (ObjectUtil.isEmpty(reportDb.getDbSource())) {
            reportDb.setDbSource("");
        }

        this.a(reportDb);
        var8 = reportDb.getId();
        this.reportDbFieldService.deleteByReportId(var8);
        List var10 = reportDb.getFieldList();
        if (c.a(var10)) {
            Iterator var11 = var10.iterator();

            while(var11.hasNext()) {
                JmReportDbField var5 = (JmReportDbField)var11.next();
                var5.setJimuReportDbId(var8);
            }

            this.reportDbFieldService.saveOrUpdateBatch(var10);
        }

        this.jmReportParamService.deleteByReportId(var8);
        List var12 = reportDb.getParamList();
        if (c.a(var12)) {
            Iterator var13 = var12.iterator();

            while(var13.hasNext()) {
                JmReportDbParam var6 = (JmReportDbParam)var13.next();
                var6.setJimuReportHeadId(var8);
            }

            this.jmReportParamService.saveOrUpdateBatch(var12);
        }

        return reportDb;
    }

    @Override
    public List<List<Map>> fieldTree(String reportId) {
        ArrayList var2 = new ArrayList();
        new JmReportDb();
        List var4 = this.reportDbDao.selectList(reportId);
        if (c.a(var4)) {
            Iterator var5 = var4.iterator();

            while(var5.hasNext()) {
                JmReportDb var6 = (JmReportDb)var5.next();
                ArrayList var7 = new ArrayList();
                HashMap var8 = new HashMap();
                var8.put("dbId", var6.getId());
                var8.put("expand", true);
                var8.put("title", var6.getDbChName());
                var8.put("code", var6.getDbCode());
                var8.put("type", var6.getDbType());
                var8.put("isList", var6.getIsList());
                List var9 = this.reportDbFieldService.getByDbId(var6.getId());
                ArrayList var10 = new ArrayList();
                HashMap var13;
                if (c.a(var9)) {
                    for(Iterator var11 = var9.iterator(); var11.hasNext(); var10.add(var13)) {
                        JmReportDbField var12 = (JmReportDbField)var11.next();
                        var13 = new HashMap();
                        var13.put("expand", true);
                        if (var12.getFieldName().equals(var12.getFieldText())) {
                            var13.put("title", var12.getFieldName());
                            var13.put("fieldText", var12.getFieldName());
                        } else {
                            var13.put("title", var12.getFieldName());
                            var13.put("fieldText", var12.getFieldText());
                        }
                    }
                }

                var8.put("children", var10);
                var7.add(var8);
                var2.add(var7);
            }
        }

        return var2;
    }

    @Override
    public boolean queryIsPage(String reportId) {
        int var2 = this.reportDbDao.getCountByReportId(reportId);
        boolean var3 = false;
        if (var2 > 0) {
            var3 = true;
        }

        return var3;
    }

    @Override
    public Map<String, Object> executeSelectSql(String sql, String dbKey, Map<String, Object> params) {
        List var4 = this.jmReportParamService.list(params.get("jimuReportHeadId").toString());
        JmReportDbParam var6;
        String var8;
        if (var4 != null && var4.size() > 0) {
            for(Iterator var5 = var4.iterator(); var5.hasNext(); sql = sql.replace("${" + var6.getParamName() + "}", var8)) {
                var6 = (JmReportDbParam)var5.next();
                Object var7 = params.get("self_" + var6.getParamName());
                var8 = "";
                if (var7 != null) {
                    var8 = var7.toString();
                } else if (var7 == null && oConvertUtils.isNotEmpty(var6.getParamValue())) {
                    var8 = var6.getParamValue();
                }
            }
        }

        HashMap var15 = new HashMap();
        Integer var16 = oConvertUtils.getInt(params.get("pageSize"), 10);
        Integer var17 = oConvertUtils.getInt(params.get("pageNo"), 1);
        var8 = "select * from (" + sql + ") jeecg_rp_temp  where 1=1";
        Object var9 = params.get("column");
        if (var9 != null) {
            var8 = var8 + " order by jeecg_rp_temp." + var9.toString() + " " + params.get("order").toString();
        }

        a.info("报表查询sql=>\r\n" + var8);
        if (ObjectUtil.isNotEmpty(dbKey)) {
            String var10 = JmreportSqlUtils.getCountSql(sql);
            Map var11 = (Map)this.jmreportDynamicDbUtil.findOne(dbKey, var10, new Object[0]);
            var15.put("total", var11.get("total"));
            JmreportDynamicDataSourceVo var12 = JmreportDataSourceCachePool.getCacheDynamicDataSourceModel(dbKey);
            String var13 = JmreportSqlUtils.createPageSqlByDBType(var12.getDbType(), var8, var17, var16);
            List var14 = this.jmreportDynamicDbUtil.findList(dbKey, var13, new Object[0]);
            var15.put("records", c.b(var14));
        } else {
            MiniDaoPage var18 = this.reportDbDao.selectPageBySql(var8, var17, var16);
            var15.put("total", var18.getResults());
            var15.put("records", c.b(var18.getResults()));
        }

        return var15;
    }

    @Override
    public Map<String, Object> executeSelectApi(String api, String method, String token) {
        HashMap var4 = new HashMap();
        JSONObject var5 = this.a(api, method, token);
        ArrayList var6 = new ArrayList();
        if (var5 != null && !"".equals(var5)) {
            String var8 = new String();
            Object var7;
            if (!var5.containsKey("data")) {
                var7 = var5;
                var8 = String.valueOf(var5);
            } else {
                Object var9 = var5.get("data");
                if (null != var9) {
                    var8 = JSON.toJSONString(var9, new SerializerFeature[]{SerializerFeature.WriteMapNullValue});
                }

                var7 = JSONObject.parse(var8, new Feature[]{Feature.OrderedField});
            }

            LinkedHashMap var14 = new LinkedHashMap();
            if (var7 instanceof JSONObject) {
                JSONObject var10 = JSON.parseObject(var8, new Feature[]{Feature.OrderedField});
                Iterator var11 = var10.keySet().iterator();

                while(var11.hasNext()) {
                    String var12 = (String)var11.next();
                    var14.put(var12, var10.get(var12));
                    var6.add(var14);
                }
            } else if (var7 instanceof JSONArray) {
                JSONArray var15 = (JSONArray)JSONArray.parse(var8, new Feature[]{Feature.OrderedField});
                if (var15.size() > 0) {
                    JSONObject var16 = var15.getJSONObject(0);
                    Iterator var17 = var16.keySet().iterator();

                    while(var17.hasNext()) {
                        String var13 = (String)var17.next();
                        var14.put(var13, var16.get(var13));
                        var6.add(var14);
                    }
                }
            }
        }

        var4.put("records", c.b(var6));
        return var4;
    }

    private List<String> a(String var1, String var2) {
        if (oConvertUtils.isEmpty(var1)) {
            return null;
        } else {
            byte var3 = 1;
            byte var4 = 1;
            MiniDaoPage var5 = this.reportDbDao.selectPageBySql(var1, var3, var4);
            List var6 = var5.getResults();
            if (var6.size() < 1) {
                throw new JimuReportException("该报表sql没有数据");
            } else {
                Set var7 = ((Map)var6.get(0)).keySet();
                ArrayList var8 = new ArrayList();
                Iterator var9 = var7.iterator();

                while(var9.hasNext()) {
                    String var10 = (String)var9.next();
                    var8.add(var10.toLowerCase());
                }

                return var8;
            }
        }
    }

    @Override
    public Map loadDbData(String dbId) {
        HashMap var2 = new HashMap();
        JmReportDb var3 = this.reportDbDao.get(dbId);
        if (var3 == null) {
            return var2;
        } else {
            List var4 = this.reportDbFieldService.getByDbId(dbId);
            List var5 = this.jmReportParamService.list(dbId);
            var2.put("dbId", dbId);
            var2.put("reportDb", var3);
            var2.put("fieldList", var4);
            var2.put("paramList", var5);
            return var2;
        }
    }

    @Override
    public List<JmReportDataSource> initDataSource(String createBy) {
        List var2 = this.jmReportDbSourceService.querySourceList(createBy);
        if (ObjectUtil.isNotEmpty(var2)) {
            Iterator var3 = var2.iterator();

            while(var3.hasNext()) {
                JmReportDataSource var4 = (JmReportDataSource)var3.next();
                String var5 = var4.getDbPassword();
                if (var5.startsWith("@JimuReport")) {
                    var4.setDbPassword(DesUtils.encode(var5.replace("@JimuReport", "")));
                }
            }
        }

        return var2;
    }

    @Override
    public void saveDbSource(JmReportDataSource sysDataSource) {
        this.jmReportDbSourceService.saveOrUpdate(sysDataSource);
    }

    @Override
    public boolean querySourceCode(JmReportDataSource sysDataSource) {
        boolean var2 = false;
        Integer var3 = 0;
        if (ObjectUtil.isNotEmpty(sysDataSource.getId())) {
            JmReportDataSource var4 = this.jmReportDbSourceService.selectById(sysDataSource.getId());
            if (var4.getCode() != null) {
                if (!var4.getCode().equals(sysDataSource.getCode())) {
                    var3 = this.jmReportDbSourceService.excelQueryCode(sysDataSource.getCode());
                    if (var3 == 0) {
                        var2 = true;
                    }
                } else {
                    var2 = true;
                }
            } else {
                var3 = this.jmReportDbSourceService.excelQueryCode(sysDataSource.getCode());
                if (var3 == 0) {
                    var2 = true;
                }
            }
        } else {
            var3 = this.jmReportDbSourceService.excelQueryCode(sysDataSource.getCode());
            if (var3 == 0) {
                var2 = true;
            }
        }

        return var2;
    }

    @Override
    public void delDataSource(JmReportDataSource sysDataSource) {
        this.jmReportDbSourceService.removeById(sysDataSource.getId());
    }

    @Override
    public List<Map<String, Object>> qurestechSql(JmReportDb jmReportDb) {
        if (jmReportDb == null) {
            return null;
        } else {
            String var2 = jmReportDb.getDbDynSql();
            List var3 = this.dbParamDao.list(jmReportDb.getId());
            JSONObject var4 = new JSONObject();
            Iterator var5 = var3.iterator();

            while(var5.hasNext()) {
                JmReportDbParam var6 = (JmReportDbParam)var5.next();
                if (oConvertUtils.isNotEmpty(var6.getParamValue())) {
                    var4.put(var6.getParamName(), var6.getParamValue());
                }
            }

            String var7 = this.jimuReportService.getBaseSql(jmReportDb.getId(), jmReportDb.getDbDynSql(), var4);
            if (oConvertUtils.isEmpty(jmReportDb.getDbSource())) {
                return this.reportDbDao.selectListBySql(var7);
            } else {
                return this.jmreportDynamicDbUtil.findList(jmReportDb.getDbSource(), var7, new Object[0]);
            }
        }
    }

    @Override
    public List<Map> parseData(Map<String, Object> map) {
        ArrayList var2 = new ArrayList();
        ArrayList var3 = (ArrayList)map.get("records");
        if (var3 != null && var3.size() >= 1) {
            LinkedHashMap var4 = (LinkedHashMap)var3.get(0);
            Integer var5 = 1;
            Iterator var6 = var4.entrySet().iterator();

            while(var6.hasNext()) {
                Map.Entry var7 = (Map.Entry)var6.next();
                String var8 = (String)var7.getKey();
                LinkedHashMap var9 = new LinkedHashMap();
                var9.put("fieldName", var8);
                var9.put("fieldText", var8);
                var9.put("widgetType", "String");
                var9.put("isShow", true);
                Integer var10 = var5;
                var5 = var5 + 1;
                var9.put("orderNum", var10);
                var2.add(var9);
            }
        }

        return var2;
    }

    @Override
    public List<Map<String, Object>> loadDataSourceTable(String dbKey) {
        List var2 = null;
        JmreportDynamicDataSourceVo var3 = JmreportDataSourceCachePool.getCacheDynamicDataSourceModel(dbKey);
        String var4 = var3.getDbType().contains("MYSQL") ? "MYSQL" : var3.getDbType();
        String var5 = JmreportSqlUtils.getAllTableSql(var4);
        if (ObjectUtil.isNotEmpty(var5)) {
            var2 = this.jmreportDynamicDbUtil.findList(dbKey, var5, new Object[0]);
            Iterator var6;
            Map var7;
            if (var4.contains("ORACLE")) {
                var6 = var2.iterator();

                while(var6.hasNext()) {
                    var7 = (Map)var6.next();
                    var7.put("Comment", var7.get("COMMENTS"));
                    var7.put("Name", var7.get("NAME"));
                }
            } else if (var4.contains("POSTGRESQL")) {
                var6 = var2.iterator();

                while(var6.hasNext()) {
                    var7 = (Map)var6.next();
                    var7.put("Comment", var7.get("comment"));
                    var7.put("Name", var7.get("name"));
                }
            }
        }

        return var2;
    }

    @Override
    public Map<String, Object> loadTableData(String dbKey, String tableName, Integer pageNo, Integer pageSize, String sql) {
        HashMap var6 = new HashMap();
        sql = c.a(sql, (Map)null);
        if (ObjectUtil.isNotEmpty(dbKey)) {
            a.info("报表查询querySql=>\r\n" + sql);
            String var7 = JmreportSqlUtils.getCountSql(sql);
            a.info("报表查询countSql=>\r\n" + var7);
            Map var8 = (Map)this.jmreportDynamicDbUtil.findOne(dbKey, var7, new Object[0]);
            var6.put("total", var8.get("total"));
            JmreportDynamicDataSourceVo var9 = JmreportDataSourceCachePool.getCacheDynamicDataSourceModel(dbKey);
            String var10 = var9.getDbType().contains("MYSQL") ? "MYSQL" : var9.getDbType();
            String var11 = JmreportSqlUtils.createPageSqlByDBType(var10, sql, pageNo, pageSize);
            a.info("报表查询pageSQL=>\r\n" + var11);
            List var12 = this.jmreportDynamicDbUtil.findList(dbKey, var11, new Object[0]);
            var6.put("records", c.b(var12));
        } else {
            MiniDaoPage var13 = this.reportDbDao.selectPageBySql(sql, pageNo, pageSize);
            var6.put("total", var13.getResults());
            var6.put("records", c.b(var13.getResults()));
        }

        return var6;
    }

    @Override
    @Transactional
    public void delDbData(String dbId) {
        this.reportDbDao.deleteById(dbId);
        this.reportDbFieldService.deleteByReportId(dbId);
        this.jmReportParamService.deleteByReportId(dbId);
    }

    private JSONObject a(String var1, String var2, String var3) {
        a.info("报表API 查询sendHttpRequest 原始API=> " + var1);
        Map var4 = this.jimuTokenClient.getUserInfo(var3);
        var1 = c.c(var1, var4);
        a.info("报表API 查询sendHttpRequest 替换后API=> " + var1);
        a.info("报表API 查询sendHttpRequest Method=> " + var2);
        new String();

        try {
            String var5;
            if ("0".equals(var2)) {
                var5 = c.b(var1, var3);
            } else {
                var5 = c.a(var1, var3, (JSONObject)null);
            }

            a.info("报表API 查询sendHttpRequest result=> " + var5);
            JSONObject var6 = JSONObject.parseObject(var5, new Feature[]{Feature.OrderedField});
            return var6;
        } catch (Exception var7) {
            var7.printStackTrace();
            return null;
        }
    }

    @Override
    public Map<String, Object> parseReportSql(String sql, String dbKey) throws JimuReportException {
        List var3 = c.b(sql);
        sql = c.a(sql, (Map)null);
        HashMap var4 = new HashMap();
        byte var5 = 1;
        byte var6 = 1;
        Object var7 = new ArrayList();
        ArrayList var8 = null;
        if (dbKey != null && !"".equals(dbKey)) {
            JmreportDynamicDataSourceVo var16 = JmreportDataSourceCachePool.getCacheDynamicDataSourceModel(dbKey);
            String var18 = JmreportSqlUtils.createPageSqlByDBType(var16.getDbType(), sql, var5, var6);
            var7 = this.jmreportDynamicDbUtil.findList(dbKey, var18, new Object[0]);
        } else {
            try {
                MiniDaoPage var9 = this.reportDbDao.selectPageBySql(sql, var5, var6);
                var7 = var9.getResults();
            } catch (Exception var15) {
                Throwable var10 = var15.getCause();
                String var11 = var15.getMessage();
                if (!var11.contains("Unknown column") && var10 instanceof SQLSyntaxErrorException || var11.contains("Invalid object name")) {
                    throw new RuntimeException("表名不存在");
                }

                var15.printStackTrace();
            }
        }

        if (var7 != null && ((List)var7).size() > 0) {
            var8 = new ArrayList();
            Map var17 = (Map)((List)var7).get(0);
            int var19 = 1;
            Iterator var20 = var17.entrySet().iterator();

            while(var20.hasNext()) {
                Map.Entry var12 = (Map.Entry)var20.next();
                String var13 = ((String)var12.getKey()).toLowerCase();
                LinkedHashMap var14 = new LinkedHashMap();
                var14.put("fieldName", var13);
                var14.put("fieldText", var13);
                var14.put("widgetType", "String");
                var14.put("orderNum", var19++);
                var8.add(var14);
            }

            var4.put("fieldList", var8);
            var4.put("paramList", var3);
        }

        return var4;
    }

    @Override
    public Result addDataSource(JmReportDataSource dataSource, HttpServletRequest request) {
        String var3 = this.jimuTokenClient.getUsername(request);
        ApiAssert.isNotEmpty("未实现JmReportTokenServiceI", var3);
        String var4 = DesUtils.decode(dataSource.getDbPassword());
        dataSource.setDbPassword("@JimuReport" + var4);
        dataSource.setCreateBy(var3);
        dataSource.setCreateTime(new Date());
        this.saveDbSource(dataSource);
        return Result.OK("操作成功！", true);
    }

    @Override
    public List<Map<String, Object>> queryTableName(String key, String tableName) {
        ArrayList var3 = new ArrayList();
        List var4 = this.loadDataSourceTable(key);
        if (StringUtils.isEmpty(tableName)) {
            return var4;
        } else {
            Pattern var5 = Pattern.compile(tableName.toLowerCase());
            Iterator var6 = var4.iterator();

            while(var6.hasNext()) {
                Map var7 = (Map)var6.next();
                Object var8 = new HashMap();
                String var9 = String.valueOf(var7.get("Name"));
                Matcher var10 = var5.matcher(var9.toLowerCase());
                if (var10.find()) {
                    var8 = var7;
                    var7.put("Name", var7.get("Name"));
                }

                if (((Map)var8).size() > 0 && null != var8) {
                    var3.add(var8);
                }
            }

            return var3;
        }
    }

    @Override
    public void updateById(JmReportDb reportDb) {
        this.reportDbDao.update(reportDb);
    }

    @Override
    public JmReportDb getById(String apiSelectId) {
        return this.reportDbDao.get(apiSelectId);
    }

    @Override
    public int getCount(String reportId, String code) {
        return this.reportDbDao.getCount(reportId, code);
    }

    public void a(JmReportDb var1) {
        if (StringUtils.isNotEmpty(var1.getId())) {
            this.reportDbDao.update(var1);
        } else {
            var1.setId(String.valueOf(SnowflakeIdWorker.generateId()));
            this.reportDbDao.insert(var1);
        }

    }
}

